package com.iursp.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iursp.conf.annotation.CacheLock;
import com.iursp.domain.model.role.AuthPlatform;
import com.iursp.domain.model.role.AuthResource;
import com.iursp.domain.model.role.RoleResource;
import com.iursp.domain.model.role.TreeNode;
import com.iursp.domain.model.user.CommonUser;
import com.iursp.domain.result.ExceptionMsg;
import com.iursp.domain.result.Response;
import com.iursp.service.resource.ResourceService;
import com.iursp.service.role.PlatformService;
import com.iursp.utils.MD5Util;
import com.iursp.utils.ResultUtils;
import com.iursp.utils.UserUtils;
import com.uih.imagecloud.frame.core.utils.JsonUtils;
import com.uih.imagecloud.frame.core.web.domain.Result;
import com.uih.imagecloud.frame.core.web.domain.Result.Status;

import groovy.util.logging.Slf4j;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/auth/roleResource")
@Slf4j
public class RoleResourceController extends BaseController {

	/**
	 * 注入ResourceService
	 */
    @Autowired 
	private  ResourceService resourceservice;
    
	@Autowired
	private PlatformService platformService;
    
    
	/**
	 * 获取资源管理节点信息
	 * @return
	 */
	@ApiOperation(value="获取资源管理节点信息 ", notes="初始化获取资源节点信息 ")
	@GetMapping(value = "/")
	public List<TreeNode> getResourceTreeNode() {
		try {
			List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
			List<AuthPlatform> platformList = platformService.queryInnerPlatform();
			if(!CollectionUtils.isEmpty(platformList)){
				for (AuthPlatform sysPlatform : platformList) {
					TreeNode treeNode = new TreeNode();
					treeNode.setId(sysPlatform.getRefid());
					treeNode.setName(sysPlatform.getPlatformName());
					treeNode.setObj(sysPlatform);
					treeNodeList.add(treeNode);
				}
			}
			/*
			 * 获取Resource节点
			 */
			List<AuthResource> resourcesList =resourceservice.getResourceNodeList();
			if(!CollectionUtils.isEmpty(resourcesList)){
				for (AuthResource resource : resourcesList) {
					TreeNode treeNode = new TreeNode();
					treeNode.setId(resource.getRefid());
					treeNode.setName(resource.getResourceName());
					treeNode.setPid(resource.getParentRefid());
					treeNode.setObj(resource);
					treeNodeList.add(treeNode);
				}
			}
			return treeNodeList;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取资源节点发生异常,错误信息为:", e);
		}
		return null;
	}
	
	@ApiOperation(value="更新资源节点", notes="根据角色id去更新资源树上对应的节点")
	@RequestMapping(value = "/{roleRefid}", method=RequestMethod.PUT,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Result updateRoleResourceInfo(@PathVariable String roleRefid){
		Result result = new Result();
        try {
        	if (!roleRefid.isEmpty()) {
        		RoleResource item = new RoleResource();
        		
        		item.setRoleRefid(roleRefid);
        		result.setMessage(JsonUtils.serialize(resourceservice.queryRoleResourceNodesByRoleRefid(item)));
        		result.setStatus(Status.OK);
			}
		} catch (Exception e) {
			result.setMessage("更新资源失败");
			result.setStatus(Status.ERROR);
			logger.error("更新资源节点发生异常,错误信息为:", e);
		}
		return result;
	}
	/**
	 * 
	 * @Title: saveRoleResourceInfo   
	 * @Description: 保存角色资源信息
	 * @param: @param roleRefid
	 * @param: @param resoureRefid
	 * @param: @return      
	 * @return: Result      
	 * @throws
	 */
	@ApiOperation(value="保存资源节点", notes="保存角色资源信息")
	@RequestMapping(value="/",method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@CacheLock(prefix = "roleResource")
	public Response saveRoleResourceInfo(@RequestParam(required = true)String roleRefid,@RequestParam(required = true)String[] resoureRefid){
		if (roleRefid.isEmpty()) {
			return ResultUtils.result("11000", "角色没选");
		}
		try {
			CommonUser userEntity = UserUtils.getUser();
			String userRefid = userEntity.getRefid();
			//删除原有的节点
			resourceservice.deleteRoleResource(roleRefid);
			RoleResource roleResource=new RoleResource();
			if (resoureRefid!=null&&resoureRefid.length>0) {
				for (int i = 0; i < resoureRefid.length; i++) {
					if (platformService.selectByPrimaryKey(resoureRefid[i])==null) {
						roleResource.setRefid(MD5Util.encrypt());
						roleResource.setRoleRefid(roleRefid);
						roleResource.setResourceRefid(resoureRefid[i]);
						roleResource.setCreateUserRefid(userRefid);
						roleResource.setModifyUserRefid(userRefid);
						resourceservice.insertRoleResource(roleResource);
					}
				}
			}
			return new Response("000000","角色资源添加成功");
		} catch (Exception e) {
			logger.error("加载资源节点发生异常,错误信息为:", e);
			return ResultUtils.result(ExceptionMsg.RoleResourceFailed);
		}
		
	}
}
